﻿using System.Threading.Tasks;
using Zo.Common;

namespace Zo.Events
{
    /// <summary>
    /// 事件处理器扩展。
    /// </summary>
    public static class EventManagerExtensions
    {
        /// <summary>
        /// 注册事件处理器。
        /// </summary>
        /// <typeparam name="TEvent">事件类型。</typeparam>
        /// <param name="eventManager">事件管理器。</param>
        /// <param name="eventHandler">事件处理器。</param>
        public static void Register<TEvent>(this IEventManager eventManager, IEventHandler<TEvent> eventHandler)
        {
            eventManager.Register(new DefaultEventHandler<TEvent>(typeof(TEvent).Name.ToLower(), eventHandler));
        }

        /// <summary>
        /// 事件处理。
        /// </summary>
        /// <param name="eventManager">事件管理器。</param>
        /// <param name="envelope">事件信息。</param>
        public static void Handle(this IEventManager eventManager, object envelope)
        {
            Check.NotNull(envelope, nameof(envelope));

            var name = envelope.GetType().Name.ToLower();

            eventManager.Handle(name, envelope);
        }

        /// <summary>
        /// 事件处理。
        /// </summary>
        /// <param name="eventManager">事件处理器。</param>
        /// <param name="envelope">事件信息。</param>
        /// <returns>事件结果。</returns>
        public static Task<IEventResult> HandleAsync(this IEventManager eventManager, object envelope)
        {
            Check.NotNull(envelope, nameof(envelope));

            return eventManager.HandleAsync(envelope.GetType().Name.ToLower(), envelope);
        }
    }
}